package client

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"zk1/common/proto/goods"
)

type Handle func(ctx context.Context, client goods.GoodsClient) (interface{}, error)

func GoodsGrpc(ctx context.Context, handle Handle) (interface{}, error) {
	conn, err := grpc.Dial("127.0.0.1:8080", grpc.WithInsecure())
	if err != nil {
		fmt.Printf("连接异常： %s\n", err)
	}
	client := goods.NewGoodsClient(conn)
	res, _ := handle(ctx, client)
	if err != nil {
		return nil, err
	}
	defer conn.Close()
	return res, nil
}

func Create(ctx context.Context, in *goods.CreateRequest) (*goods.CreateResponse, error) {
	goodsGrpc, err := GoodsGrpc(ctx, func(ctx context.Context, client goods.GoodsClient) (interface{}, error) {
		create, err := client.Create(ctx, in)
		if err != nil {
			return nil, err
		}
		return create, nil
	})
	if err != nil {
		return nil, err
	}
	return goodsGrpc.(*goods.CreateResponse), nil
}

func List(ctx context.Context, in *goods.ListRequest) (*goods.ListResponse, error) {
	goodsGrpc, err := GoodsGrpc(ctx, func(ctx context.Context, client goods.GoodsClient) (interface{}, error) {
		list, err := client.List(ctx, in)
		if err != nil {
			return nil, err
		}
		return list, nil
	})
	if err != nil {
		return nil, err
	}
	return goodsGrpc.(*goods.ListResponse), nil
}
